package com.cnbbx.cnbbx_web.aop;

import com.cnbbx.cnbbx_web.annotation.NoRepeatSubmit;
import com.cnbbx.cnbbx_web.vo.JsonReturn;
import com.cnbbx.cnbbx_web.utils.MD5Util;
import com.google.common.cache.Cache;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * aop解析注解
 */
@Aspect
@Component
@Slf4j
public class NoRepeatSubmitAop {
    @Autowired
    private Cache<String, Integer> cache;

    @Around("execution(* com.cnbbx..*Controller.*(..)) && @annotation(nrs)")
    public Object around(ProceedingJoinPoint pjp, NoRepeatSubmit nrs) {
        try {
            Object[] obj = pjp.getArgs();
            Signature signature = pjp.getSignature();
            String key = MD5Util.encode(signature.toShortString() + ":" + Arrays.toString(obj));
            if (cache.getIfPresent(key) == null) {
                Object o = pjp.proceed();
                cache.put(key, 0);
                return o;
            } else {
                return new JsonReturn(400, "重复提交");
            }
        } catch (Throwable e) {
            e.printStackTrace();
            return new JsonReturn(400, "验证重复提交时出现未知异常");
        }
    }

}